package com.sc.common.service;

import com.alibaba.fastjson.JSONObject;
import com.sc.common.context.DefaultBusinessContext;
import com.sc.common.dao.CommonMapper;
import com.sc.common.dto.ExcelDto;
import com.sc.common.dto.WebResponseDto;
import com.sc.common.entity.admin.distributedfile.SysDistributedFile;
import com.sc.common.util.MyStringUtils;
import com.sc.common.util.cache.DataDictionaryUtil;
import com.sc.easyexcel.definition.ExcelDefinitionReader;
import com.sc.easyexcel.factory.DefinitionFactory;
import com.sc.easyexcel.factory.xml.XMLDefinitionFactory4commonExport;
import com.sc.easyexcel.resolver.poi.POIExcelResolver4commonExport;
import com.sc.easyexcel.result.ExcelExportResult;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * Created by wust on 2019/9/7.
 */
@Service("exportExcelServiceImpl")
public class ExportExcelServiceImpl extends POIExcelResolver4commonExport implements ExportExcelService {

    static Logger logger = LogManager.getLogger(ExportExcelServiceImpl.class);

    @Autowired
    private CommonMapper commonMapper;

    @Autowired
    private MinioStorageApiService minioStorageApiService;

    @Autowired
    private MinioStorageService minioStorageServiceImpl;

    @Override
    public WebResponseDto export(JSONObject jsonObject) {
        WebResponseDto responseDto = new WebResponseDto();
        responseDto.setCode("A100502");

        DefaultBusinessContext ctx = jsonObject.getObject("ctx",DefaultBusinessContext.class);
        DefaultBusinessContext.getContext().setLocale(ctx.getLocale());

        ExcelDto excelDto = jsonObject.getObject("excelDto",ExcelDto.class);

        BeanUtils.copyProperties(excelDto,super.excelParameters);

        ByteArrayOutputStream bos = null;
        InputStream is = null;
        try {
            String batchNo = excelDto.getBatchNo();
            String fileName = batchNo + "." + excelParameters.getFileType();

            ExcelExportResult excelExportResult = super.createWorkbook();
            Workbook wb = excelExportResult.getWorkbook();
            bos = new ByteArrayOutputStream();
            wb.write(bos);
            byte[] byteArray = bos.toByteArray();
            is = new ByteArrayInputStream(byteArray);

            String objectName = UUID.randomUUID().toString();
            long size = is.available();
            SysDistributedFile distributedFile = minioStorageApiService.upload(objectName,is,size,null,null,null,fileName,excelParameters.getFileType(),"sc-admin.sys_import_export",minioStorageServiceImpl);
            JSONObject jsonObjectResult = new JSONObject();
            jsonObjectResult.put("fileId",distributedFile.getId());
            jsonObjectResult.put("size",size);
            jsonObjectResult.put("name",fileName);
            responseDto.setObj(jsonObjectResult);
        } catch (Exception e) {
           logger.error(e);
            responseDto.setFlag(WebResponseDto.INFO_ERROR);
            responseDto.setCode("A100504");
            if(MyStringUtils.isNotBlank(e.getMessage())){
                int length = e.getMessage().length() >= 500 ? 500 : e.getMessage().length();
                responseDto.setMessage(e.getMessage().substring(0,length));
            }else{
                int length = e.toString().length() >= 500 ? 500 : e.toString().length();
                responseDto.setMessage("导出失败:" + e.toString().substring(0,length));
            }
        }finally {
            if(bos != null){
                try {
                    bos.close();
                } catch (IOException e) {
                }
            }
            if(is != null){
                try {
                    is.close();
                } catch (IOException e) {
                }
            }
        }
        return responseDto;
    }


    @Override
    protected ExcelDefinitionReader getExcelDefinition() {
        DefinitionFactory definitionReaderFactory = new XMLDefinitionFactory4commonExport("easyexcel/export/xml/" + excelParameters.getXmlName() + ".xml");
        return definitionReaderFactory.createExcelDefinitionReader();
    }

    @Override
    protected List<Map<String, Object>> findBySql(Map<String, Object> parseParameters) {
        return this.commonMapper.findBySql(parseParameters);
    }

    @Override
    protected String getLookupItemNameByCode(String code) {
        DefaultBusinessContext ctx = DefaultBusinessContext.getContext();
        String lang = "zh_CN";
        if(ctx.getLocale() != null){
            lang = ctx.getLocale().toString();
        }
        return DataDictionaryUtil.getLookupNameByCode(lang,code);
    }
}
